
declare var badge: any;
declare var cordova:any;
export class WebSocketClient {
    private ws:any;
    private lockReconnect:any = false;
    private lockReconnectCount:number=0;
    private url:any='';
    constructor(url) {
        this.url= url;
      this.myNotification(url)
    }
    myNotification(url){
        this.ws = new WebSocket(url);
        this.ws.onopen = this.onOpen.bind(this);
        this.ws.onmessage = this.onMessage.bind(this);
        this.ws.onerror = this.onError.bind(this);
        this.ws.onclose = this.onClose.bind(this);
    }
    onOpen(event) {
        // 连接打开时的回调
        console.log('WebSocket connected:', event);
    }

    onMessage(event) {
        // 收到消息时的回调
        console.log('WebSocket message received:', event.data);
        //alert( event.data);
        cordova.plugins.notification.local.schedule({
            title: 'Single ILocalNotification'+event.data,
            text: "测试数据",
            foreground: true
        });


        cordova.plugins.notification.local.schedule({
            id: 1,
            title: 'My first notification',
            androidChannelId: "my_channel_01",
            androidChannelName: "My Channel Name"
        });

        badge.requestPermission(function (granted) {
            alert('权限是否被授予: ' + granted);
        });
        badge.badge.setBadgeCount(Number(event.data))
    }

    onError(event) {
        // 出现错误时的回调
        console.error('WebSocket error:', event);
        if(this.lockReconnectCount===3) return;
        this.reconnect();
    }

    onClose(event) {
        // 连接关闭时的回调
        console.log('WebSocket closed:', event);
        this.reconnect();
    }

    send(message) {
        // 发送消息的方法
        this.ws.send(message);
    }

    close() {
        // 关闭连接的方法
        this.ws.close();
    }
    reconnect() {
        this.lockReconnectCount +=1;
        if (this.lockReconnect) return;
        this.lockReconnect = true;
        //没连接上会一直重连，设置延迟避免请求过多
        setTimeout(()=>{
            this.myNotification(this.url);
            this.lockReconnect = false;
        },1000)

    }

}




